<template>
    <div class='tab-search-wrap'>
        <v-tabs v-model='tab' :height='30' :right='false' class='tab' fixed-tabs>
            <v-tab
                :style='{"font-size":"12px", "padding": "0px 5px", "min-width": "40px"}'
                v-for='i in tabs'
                :key='i.key'
                :href='`#tab-${i.key}`'
                @click='clickHandler(i)'
            >
                <span class='text-capitalize'>{{ i.key }}</span>
                <span class='tab-text-icon'></span>
            </v-tab>
            <template v-for='(item, index) in $data._component'>
                <v-tab-item
                    :class='["tab" + (index + 1), "tab"]'
                    v-if='show'
                    :value='"tab-" + tabs[index].key'
                    :key='index'
                >
                    <component :is='item'></component>
                </v-tab-item>
            </template>
        </v-tabs>
        <div v-show='show' class='action-btn'>
            <div class='annuler' @click='annulerHandler'>Annuler</div>
            <div class='subtitle text-capitalize'>
                <div class='subtitle-count'>{{resultLen}}</div>
                <div class='subtitle-title'>annonces</div>
            </div>
            <v-btn
                color='error text-capitalize'
                class='rechercher'
                @click='commitClickHandler'
                dark
            >Rechercher</v-btn>
        </div>
    </div>
</template>


<script>
import TabBudget from './tabs/budget';
import TabSurface from './tabs/surface';
import TabPieces from './tabs/pieces';
import TabEtage from './tabs/etage';

import { mapState, mapMutations, mapGetters } from 'vuex';

import searchList from '../../api/search';

const { search } = searchList;
import { antiShake } from '../../utils/utilFun';
import { reject } from 'q';
export default {
    props: {
        show: {
            type: Boolean,
            default: false,
        },
        isViewList: {
            type: Boolean,
            required: true,
        },
    },
    data() {
        return {
            tab: null,
            tabs: [
                { key: 'Budget', mapping: 'budgetData' },
                { key: 'Surface', mapping: 'surfaceData' },
                { key: 'Pièces', mapping: 'piecesData' },
                { key: 'Etage', mapping: 'etageData' },
            ],
            nowTabShow: null,
            minSurface: Infinity,
            maxSurface: -Infinity,
            minBudget: Infinity,
            maxBudget: -Infinity,
            timer: null,
            oneInit: true,
            originData: null,
            isClickBtn: false,
            _component: [TabBudget, TabSurface, TabPieces, TabEtage],
            resultLen: 0,
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        ...mapMutations({
            commitSearchState: 'searchData/commitState',
            commitListState: 'viewList/commitListState',
            commitSearchTypeData: 'searchData/commitTypeData',
            searchBackState: 'searchData/backState',
        }),
        // 查找数据找到最小高和宽
        async init() {
            const timer = this.timer;
            if (!this.originData) {
                this.originData = {
                    ...JSON.parse(
                        JSON.stringify({
                            budgetRange: this.budgetData.range,
                            surfaceRange: this.surfaceData.range,
                            piecesValue: this.piecesData.value,
                            etageValue: this.etageData.value,
                        })
                    ),
                };
            }
            const helpList = await this.getListData();
            if (timer) {
                clearTimeout(timer);
            }

            if (!helpList.length) {
                this.timer = setTimeout(() => {
                    this.init();
                }, 15000);
                return;
            }
            if (this.oneInit) {
                this.oneInit = false;
                const budgetRange = this.budgetData.range;
                const surfaceRange = this.surfaceData.range;
                helpList.forEach(item => {
                    const price = Number(item.price);
                    if (price > this.maxBudget) {
                        this.maxBudget = price;
                    } else if (price < this.minBudget) {
                        this.minBudget = price;
                    }

                    if (item.surface > this.maxSurface) {
                        this.maxSurface = item.surface;
                    } else if (item.surface < this.minSurface) {
                        this.minSurface = item.surface;
                    }
                });

                const budgetData = {
                    min: this.minBudget,
                    max: this.maxBudget,
                };
                const surfaceData = {
                    min: this.minSurface,
                    max: this.maxSurface,
                };

                if (budgetRange[0] < budgetData.min || budgetRange[1] > budgetData.max) {
                    const range = [
                        this.budgetData.min === budgetRange[0] ? budgetData.min : this.budgetData.min,
                        this.budgetData.max === budgetRange[1] ? budgetData.max : this.budgetData.max,
                    ];

                    budgetData.range = range;
                }
                if (surfaceRange[0] < surfaceData.min || surfaceRange[1] > surfaceData.max) {
                    const range = [
                        this.surfaceData.min === surfaceRange[0] ? surfaceData.min : this.surfaceData.min,
                        this.surfaceData.max === surfaceRange[1] ? surfaceData.max : this.surfaceData.max,
                    ];
                    surfaceData.range = range;
                }
                this.commitSearchTypeData({
                    k: 'budgetData',
                    data: budgetData,
                });
                this.commitSearchTypeData({
                    k: 'surfaceData',
                    data: surfaceData,
                });
            }

            this.commitListState({
                k: 'helpList',
                v: helpList,
            });

            this.timer = setTimeout(() => {
                this.init();
            }, 10000);
        },
        async getListData() {
            const budgetRange = this.originData.budgetRange;
            const surfaceRange = this.originData.surfaceRange;
            const piecesValue = this.originData.piecesValue || '';
            const etageValue = this.originData.etageValue || '';
            try {
                return (await search()).data || [];
            } catch (error) {
                return [];
            }
        },
        clickHandler(tabItem) {
            this.nowTabShow = tabItem.mapping;
            this.$emit('update:show', true);
        },
        annulerHandler() {
            this.searchBackState({ k: this.nowTabShow });
            return;
        },
        async commitClickHandler() {
            if (!this.isViewList) {
                this.$emit('update:isViewList', true);
            }
            this.isClickBtn = true;
            const list = await this.updateFilterList();
            this.commitListState({
                k: 'list',
                v: list,
            });
        },
        async updateFilterList() {
            const budgetRange = this.budgetData.range;
            const surfaceRange = this.surfaceData.range;
            const piecesValue = this.piecesData.value;
            const etageValue = this.etageData.value;
            let list = this.helpList;

            return new Promise(resolve => {
                this.$nextTick(() => {
                    const isInit = Object.keys(this.getInit).every(i => this.getInit[i]);
                    !this.getInit.budget &&
                        (list = list.filter(item => {
                            return Number(item.price) >= budgetRange[0] && Number(item.price) <= budgetRange[1];
                        }));

                    !this.getInit.surface &&
                        (list = list.filter(item => {
                            return Number(item.surface) >= surfaceRange[0] && Number(item.surface) <= surfaceRange[1];
                        }));

                    !this.getInit.pieces &&
                        piecesValue.length !== 0 &&
                        (list = list.filter(item => {
                            return piecesValue.indexOf(item.piece.trim()) !== -1;
                        }));
                    !this.getInit.etage &&
                        etageValue.length !== 0 &&
                        (list = list.filter(item => {
                            return etageValue.indexOf(item.etage.trim()) !== -1;
                        }));
                    resolve(list);
                });
            });
        },
    },
    computed: {
        ...mapState({
            initCount: state => state.searchData.initCount,
            budgetData: state => state.searchData.budgetData,
            surfaceData: state => state.searchData.surfaceData,
            piecesData: state => state.searchData.piecesData,
            etageData: state => state.searchData.etageData,
            list: state => state.viewList.list,
            helpList: state => state.viewList.helpList,
        }),
        ...mapGetters({
            getInit: 'searchData/getInit',
        }),
    },
    watch: {
        'budgetData.range': antiShake(async function() {
            this.resultLen = (await this.updateFilterList()).length;
        }),
        'surfaceData.range': antiShake(async function() {
            this.resultLen = (await this.updateFilterList()).length;
        }),
        'piecesData.value': async function() {
            this.resultLen = (await this.updateFilterList()).length;
        },
        'etageData.value': async function() {
            this.resultLen = (await this.updateFilterList()).length;
        },
    },
    components: {
        TabBudget,
        TabSurface,
        TabPieces,
        TabEtage,
    },
};
</script>



<style lang='scss' scoped>
.tab-search-wrap {
    background: #fff;
    .action-btn {
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;
        padding: 3px 10px;
        margin-top: 20px;
        .annuler {
            cursor: pointer;
            transition: color 0.5s ease;
            &:hover {
                color: red;
            }
        }

        .subtitle {
            position: relative;
            box-sizing: border-box;
            padding-top: 15px;
            font-size: 12px;
            .subtitle-count {
                position: absolute;
                top: -15px;
                font-size: 20px;
                left: 50%;
                transform: translateX(-50%);
            }
        }
        .rechercher {
            border-radius: 20px;
            border: 1px solid transparent;
            &:hover {
                background-color: #f40034 !important;
            }
        }
    }
    .tab {
        .tab-text-icon {
            background: url(/image/top_03.png);
            width: 10px;
            height: 8px;
            background-repeat: no-repeat;
            margin-left: 3px;
            background-size: 80% 80%;
            margin-top: 4px;
        }
    }
}
</style>


<style lang="scss">
.tab-search-wrap {
    .tab {
        .tab-item {
            box-sizing: border-box;
            padding: 5px 15px 0px 15px;
        }
        .tab-item-content {
            margin-top: 35px;
        }
        .tab-item-title {
            font-weight: 900;
        }
    }
    .tab.tab1,
    .tab.tab2 {
        .tab-item-content {
            position: relative;
            box-sizing: border-box;
            padding: 0px 20px;

            .num-view {
                position: absolute;
                display: flex;
                width: 100%;
                font-size: 14px;
                justify-content: space-between;
                box-sizing: border-box;
                padding: 0px 20px;
                left: 0px;
                bottom: 0px;
            }
        }
    }
    .tab.tab3,
    .tab.tab4 {
        .tab-item-content {
            margin-top: 0px;
            .text-capitalize {
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: space-between;
            }
        }
    }
    .v-slide-group__next {
        display: none !important;
    }
    .v-slide-group__prev {
        display: none !important;
    }
}
</style>